package gsar.client;


import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;


/*
Copyright (c) 2009, Eric Eaton, University of Maryland Baltimore County
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the University of Maryland Baltimore County nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/** A sample search and rescue client that wanders randomly.
 *   
 * Specifically, the agent follows these rules:
 *    - If the agent is next to a person and isn't carrying anything,
 *      and the person is not at an exit, it picks up the person (if there
 *      are multiple people, it picks up the first one in the list sent by
 *      the server).
 *    - If the agent is next to an unoccupied exit and is carrying a
 *      person, it drops the person off at the exit.
 *    - If neither of the above apply, the agent picks a random square
 *      to move into, from the squares directly reachable from its current
 *      location (excluding occupied squares).  The agent
 *      attempts to avoid moving back to locations that were visited
 *      previously.
 *    - On the off chance that the agent can't move, it does nothing.
 *
 * The agent does not check whether its actions are successful.
 *
 * DO NOT MODIFY THE CONTENTS OF THIS FILE -- it may be overwritten in
 * later releases of the Search and Rescue simulator.
 *
 * @author Eric Eaton, Aaron Curtis
 */
public class RandomAgent extends Client {
	
	/** The delay for thinking in milliseconds.  Each iteration
	 * of the chooseAction() function will delay this much.  Set
	 * to zero for no delay, or 1000-2000 for a reasonable delay.
	 */
	protected int m_delayForThinking = 0;
	
	protected Random m_randGenerator = new Random(System.currentTimeMillis());
	
	public static void main(String[] args) {
		main(new RandomAgent(), args);
	}

	@Override
	protected GWAction chooseAction(Perceptions perceptions) {
		
		// display the current perceptions
		System.out.println("Current time:  "+getCurrentTime());
		System.out.println("Perceptions:  ");
		System.out.println(perceptions);
		System.out.println();
		System.out.println("Perceived locations:  "+perceptions.listPerceivedCoordinates());
		System.out.println("Perceived objects:  "+perceptions.listPerceivedObjects());
	
		// determine if we're carrying a victim
		if (perceptions.getLastAction() != null && 
			perceptions.getLastAction().getAction().getName().equalsIgnoreCase("PICKUP") &&
			perceptions.getLastAction().getStatus().toString().equalsIgnoreCase("SUCCESS")) {
			m_hasPerson = true;
			// empty the history
			m_visitedCoordinates.removeAll(m_visitedCoordinates);
		} else if (perceptions.getLastAction() != null &&
				   perceptions.getLastAction().getAction().getName().equalsIgnoreCase("DROPOFF") &&
			       perceptions.getLastAction().getStatus().toString().equalsIgnoreCase("SUCCESS")) {
			m_hasPerson = false;
			// empty the history
			m_visitedCoordinates.removeAll(m_visitedCoordinates);
	    }
		
		// mark the current cell as visited
		markVisited(perceptions.getCurrentLocation());
		
		
		// figure out which cells are directly reachable from the current position
		Set<GWCell> nearbyCells = new HashSet<GWCell>();
		Set<GWCoordinate> adjacentCoordinates = getMap().getAdjacentCoordinates(perceptions.getCurrentLocation());
		for (GWCoordinate coord : adjacentCoordinates) {
			nearbyCells.add(perceptions.getPerceivedCell(coord));
		}
				
		
		// see if any of the adjacent cells contains a victim
		Set<GWCell> cellsWithVictims = new HashSet<GWCell>();
		for (GWCell cell : nearbyCells) {
			if (cell.hasOccupant() && cell.getOccupant().getName().equalsIgnoreCase("person")
				&& !isExit(cell))
				cellsWithVictims.add(cell);
		}
		
		// see if any of the adjacent cells is an exit
		Set<GWCell> exitCells = new HashSet<GWCell>();
		for (GWCell cell : nearbyCells) {
			if (isExit(cell))
				exitCells.add(cell);
		}
		
		// determine the cells where the agent can move from here
		Set<GWCell> openCells = new HashSet<GWCell>();
		for (GWCell cell : nearbyCells) {
			if (!cell.hasOccupant())
				openCells.add(cell);
		}

		// filter the open cells by removing those in the history
		List<GWCell> preferredCells = new ArrayList<GWCell>();
		for (GWCell cell : openCells) {
			if (!wasVisited(cell.getCoordinates()))
				preferredCells.add(cell);
		}

		// if there are no preferred cells, include the open cells
		if (preferredCells.isEmpty())
			preferredCells.addAll(openCells);
		
		System.out.println("HasPerson? = "+m_hasPerson);
		System.out.println("Cells with victims = "+cellsWithVictims);
		System.out.println("Preferred Cells = " +preferredCells);
		System.out.println("Exit cells = "+exitCells);
		
		// slow the random agent down a bit
		if (m_delayForThinking >= 0) {
			try {
				Thread.sleep(m_delayForThinking);
			} catch (InterruptedException e) {}
		}
		
		//// determine the action to take
		
		// if the agent is not carrying a person and there is one nearby, pick it up
		GWAction action = null;
		if (!m_hasPerson && !cellsWithVictims.isEmpty()) {
			GWCell targetCell = cellsWithVictims.iterator().next();
			action = new GWAction("PICKUP", 
					              GWCoordinate.getDirection(perceptions.getCurrentLocation(),
					            	  	                   targetCell.getCoordinates()));
		}
		// if we're carrying a person and there's an exit nearby, drop off the victim
		else if (m_hasPerson && !exitCells.isEmpty()) {
			GWCell targetCell = exitCells.iterator().next();
			action = new GWAction("DROPOFF",
					              GWCoordinate.getDirection(perceptions.getCurrentLocation(),
					            	  	                   targetCell.getCoordinates()));
		}
		// otherwise, wander randomly
		else if (!preferredCells.isEmpty()) {
			// pick a random preferred cell
			Collections.shuffle(preferredCells, m_randGenerator);
			GWCell targetCell = preferredCells.iterator().next();
			GWDirection direction = GWCoordinate.getDirection(perceptions.getCurrentLocation(),
                      										  targetCell.getCoordinates());
			if (direction == null) {
				System.out.println("Direction from "+perceptions.getCurrentLocation() +" to "+targetCell.getCoordinates()+" is null.");
			}
			action = new GWAction("MOVE", direction);
		}
		// otherwise, do nothing if there are no options
		else {
			action = new GWAction("NOOP");
		}
	     
		// print out the chosen action and return it
		System.out.println("Choosing action:  "+action);
		System.out.println();
		System.out.println();
		
		return action;
	}


	@Override
	protected void initialize() {
		System.out.println("Agent initialization:  done.");
		System.out.println("Waiting for the simulation to start...");
	}


	@Override
	protected void processResult(double score) {
		System.out.println("Final score:  "+score+" rescued victims.");
	}
	

	private int m_historySize = 8;
	private boolean m_hasPerson = false;
	private LinkedList<GWCoordinate> m_visitedCoordinates = new LinkedList<GWCoordinate>();
	

	/** Utility function to tell if a cell is an exit
	 * @param cell the cell
	 * @return whether the cell is an exit
	 */
	protected boolean isExit(GWCell cell) {
		return (cell.hasMarker() && cell.getMarker().equalsIgnoreCase("EXIT"));
	}
	
	
	/** Utility function to tell if a location was visited in the known history
	 * @param coord the location
	 * @return whether the location was visited in the known history
	 */
	protected boolean wasVisited(GWCoordinate coord) {
		return m_visitedCoordinates.contains(coord);
	}

	
	/** Utility function to add some coordinates to the agent's history
	 * @param coord the coordinate
	 */
	protected void markVisited(GWCoordinate coord) {
		m_visitedCoordinates.add(coord);
		
		// remove the oldest coordinates if the history gets too large
		if (m_visitedCoordinates.size() > m_historySize) {
			m_visitedCoordinates.remove();
		}
	}


}
